package com.jeesite.modules.app.mockexam.theory.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.beust.jcommander.internal.Lists;
import com.jeesite.modules.sys.entity.Post;
import com.jeesite.modules.sys.service.PostService;
import com.jeesite.modules.zx.audio.bank.entity.TaudioBank;
import com.jeesite.modules.zx.audio.bank.service.TaudioBankService;
import com.jeesite.modules.zx.options.bank.entity.ToptionsBank;
import com.jeesite.modules.zx.options.bank.service.ToptionsBankService;
import com.jeesite.modules.zx.picture.bank.entity.TpictureBank;
import com.jeesite.modules.zx.picture.bank.service.TpictureBankService;
import com.jeesite.modules.zx.problem.bank.entity.TproblemBank;
import com.jeesite.modules.zx.problem.bank.service.TproblemBankService;
import com.jeesite.modules.zx.reading.bank.entity.TreadingBank;
import com.jeesite.modules.zx.reading.bank.service.TreadingBankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mapper.JsonMapper;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.modules.app.mockexam.theory.entity.AppExaminateTheory;
import com.jeesite.modules.app.mockexam.theory.record.entity.AppMockexamTheoryRecord;
import com.jeesite.modules.app.mockexam.theory.record.service.AppMockexamTheoryRecordService;
import com.jeesite.modules.app.mockexam.theory.service.AppExaminateTheoryService;
import com.jeesite.modules.app.mockexam.theory.user.entity.TmockexamTheoryUser;
import com.jeesite.modules.app.mockexam.theory.user.service.TmockexamTheoryUserService;
import com.jeesite.modules.conf.AppController;
import com.jeesite.modules.conf.MessageCode;
import com.jeesite.modules.zx.question.bank.entity.TquestionBank;
import com.jeesite.modules.zx.question.bank.service.TquestionBankService;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 理论模拟考试
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/app/mockexam/theory/")
public class AppMockexamTheoryController {
	@Autowired
	private AppExaminateTheoryService appExaminateTheoryService;
	@Autowired
	private AppMockexamTheoryRecordService appMockexamTheoryRecordService;
	@Autowired
	private TmockexamTheoryUserService tmockexamTheoryUserService;
	@Autowired
	private TquestionBankService tquestionBankService;
	@Autowired
	private TproblemBankService tproblemBankService;
	@Autowired
	private ToptionsBankService toptionsBankService;

	@Autowired
	private PostService postService;

	@RequestMapping(value = "findList")
	public void findList(AppExaminateTheory entity, Model model,HttpServletRequest request,HttpServletResponse response) {
		List<AppExaminateTheory> findList = appExaminateTheoryService.findList(entity);
		if (findList.size()>0){
			findList.forEach(item->{
				String post = item.getPost();
				if (post!=null){
					Post post1 = new Post();
					post1.setPostCode(post);
					post1 = postService.get(post1);
					item.setPost(post1.getPostName());
				}
			});
		}
		JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(findList));
		AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
	}
	
	 @RequestMapping(value = "subjectList")
	 public void subjectList(AppExaminateTheory entity, Model model,HttpServletRequest request,HttpServletResponse response) {
	  List<AppExaminateTheory> subjList = appExaminateTheoryService.findList(entity);
	  
	  for(AppExaminateTheory subject:subjList){
	   String suId=subject.getId();
	   AppExaminateTheory appExaminateTheory=new AppExaminateTheory();
	   appExaminateTheory.setParentCode(suId);
	   List<AppExaminateTheory> questionList = appExaminateTheoryService.findList(appExaminateTheory);
	   List<String> subidList=new ArrayList<>();
	   for(AppExaminateTheory question:questionList){
	    String objName = question.getObjName();
	    subidList.add(objName);
	   }
	   if(subidList.size()>0){
	    TquestionBank quebank=new TquestionBank();
	    quebank.getSqlMap().getWhere().and("id", QueryType.IN, subidList);
	    List<TquestionBank> quetbankList = tquestionBankService.findList(quebank);
	    subject.setQuetbankList(quetbankList);
	   }
	   
	  }
	  JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(subjList));
	  AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
	 }
	
	/**
	 * 查询标题和问题
	 * @param post
	 * @param model
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "subjectListNew")
	public void subjectListNew(@RequestParam(value = "parentCode",required=true) String parentCode,
							@RequestParam(value = "post") String post,
							@RequestParam(value = "topicType") String topicType,
							Model model, HttpServletRequest request, HttpServletResponse response) {
		AppExaminateTheory entity = new AppExaminateTheory();
		entity.setParentCode(parentCode);
		entity.setPost(post);
		List<AppExaminateTheory> subjList = appExaminateTheoryService.findList(entity);
		List<Integer> objTypeList = Lists.newArrayList(3,4,5);
		for(AppExaminateTheory subject:subjList){
			String suId=subject.getId();
			Integer objType = subject.getObjType();
			AppExaminateTheory appExaminateTheory=new AppExaminateTheory();
			appExaminateTheory.setParentCode(suId);
			List<AppExaminateTheory> questionList = appExaminateTheoryService.findList(appExaminateTheory);
			List<String> subidList=new ArrayList<>();
			for(AppExaminateTheory question:questionList){
				String objName = question.getObjName();
				subidList.add(objName);
			}
			if(subidList.size()>0) {
			    if (objTypeList.contains(objType)){
					TproblemBank problemBank = new TproblemBank();
					problemBank.getSqlMap().getWhere().and("id", QueryType.IN, subidList);
					List<TproblemBank> quetbankList = tproblemBankService.findList(problemBank);
					if (quetbankList!=null && quetbankList.size()>0){
						quetbankList.forEach(item->{
							ToptionsBank toptionsBank = new ToptionsBank();
							toptionsBank.setProblemId(item.getId());
							List<ToptionsBank>  toptionsBankList = toptionsBankService.findList(toptionsBank);
							item.setToptionsBankList(toptionsBankList);
						});
					}
					subject.setProblemBankList(quetbankList);
				}else {
					TquestionBank quebank=new TquestionBank();
					quebank.getSqlMap().getWhere().and("id", QueryType.IN, subidList);
					List<TquestionBank> quetbankList = tquestionBankService.findList(quebank);
					subject.setQuetbankList(quetbankList);
				}
			}
		}
		JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(subjList));
		AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
	}
	@RequestMapping(value = "subjectRecordList")
	public void subjectRecordList(AppExaminateTheory entity, Model model,HttpServletRequest request,HttpServletResponse response) {
		List<AppExaminateTheory> subjList = appExaminateTheoryService.findList(entity);
		String theoryId=request.getParameter("theoryId");
		if(StringUtils.isBlank(theoryId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "理论标识");
			return;
		}
		String userId=request.getParameter("userId");
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			return;
		}
		for(AppExaminateTheory subject:subjList){
			String suId=subject.getId();
			AppExaminateTheory appExaminateTheory=new AppExaminateTheory();
			appExaminateTheory.setParentCode(suId);
			List<AppExaminateTheory> questionList = appExaminateTheoryService.findList(appExaminateTheory);
			List<String> subidList=new ArrayList<>();
			for(AppExaminateTheory question:questionList){
				String objName = question.getObjName();
				subidList.add(objName);
			}
			if(subidList.size()>0){			
			TquestionBank quebank=new TquestionBank();
			quebank.getSqlMap().getWhere().and("id", QueryType.IN, subidList);
			List<TquestionBank> quetbankList = tquestionBankService.findList(quebank);
			for(TquestionBank question:quetbankList){
				String id = question.getId();
				AppMockexamTheoryRecord theoryRecord=new AppMockexamTheoryRecord();
				theoryRecord.setTheoryId(theoryId);
				theoryRecord.setPostId(entity.getParentCode());
				theoryRecord.setUserId(userId);
				theoryRecord.setQuestionId(id);
				List<AppMockexamTheoryRecord> findList = appMockexamTheoryRecordService.findList(theoryRecord);
				if(findList.size()>0){
					AppMockexamTheoryRecord arecord = findList.get(0);
					String answerId = arecord.getAnswerId();
					BigDecimal score = arecord.getScore();
					question.setAnswer(answerId);
					question.setScore(score.doubleValue());
					if(StringUtils.isNotBlank(answerId)){
						String[] split = answerId.split(",");
						for(String key:split){
						    if(key.equals("1")){
						    	question.setAnswer1("1");
						    }
						    if(key.equals("2")){
						    	question.setAnswer2("2");
						    }
						    if(key.equals("3")){
						    	question.setAnswer3("3");
						    }
						    if(key.equals("4")){
						    	question.setAnswer4("4");
						    }
						    if(key.equals("5")){
						    	question.setAnswer5("5");
						    }
						}
					}
				}else{
				    //没答题
                    question.setScore(0.0);
                }
			}
			subject.setQuetbankList(quetbankList);
		  }
		}
		JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(subjList));
		AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
	}
	@RequestMapping(value = "listQuestion")
	public void listQuestion(AppExaminateTheory entity, Model model,HttpServletRequest request,HttpServletResponse response) {
		List<AppExaminateTheory> findList = appExaminateTheoryService.findList(entity);
		List<String> list=new ArrayList<>();
		for(AppExaminateTheory theory:findList){
			String objName = theory.getObjName();
			list.add(objName);
		}
		TquestionBank question=new TquestionBank();
		question.getSqlMap().getWhere().and("id", QueryType.IN,list);
		List<TquestionBank> findList2 = tquestionBankService.findList(question);
		JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(findList2));
		AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
	}
	@RequestMapping(value="questionList")
	public void questionList(AppExaminateTheory entity, Model model,HttpServletRequest request,HttpServletResponse response){
		String theoryId=request.getParameter("theoryId");
		if(StringUtils.isBlank(theoryId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "查询标识");
			return;
		}
		String userId=request.getParameter("userId");
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			return;
		}
		AppMockexamTheoryRecord appMockexamTheoryRecord=new AppMockexamTheoryRecord();
		appMockexamTheoryRecord.setTheoryId(theoryId);
		appMockexamTheoryRecord.setUserId(userId);
		
		List<AppExaminateTheory> findList = appExaminateTheoryService.findList(entity);
		for(AppExaminateTheory aet:findList){
			String id = aet.getId();
			appMockexamTheoryRecord.setQuestionId(id);
			List<AppMockexamTheoryRecord> findList2 = appMockexamTheoryRecordService.findList(appMockexamTheoryRecord);
			for(AppMockexamTheoryRecord record: findList2){
				BigDecimal score = record.getScore();
				aet.setScore(score);
			}
		}
		
		JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(findList));
		AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
	}
	@RequestMapping(value = "options")
	public void options(AppExaminateTheory entity,HttpServletRequest request,HttpServletResponse response) {
		String parentCode = entity.getParentCode();
		if(StringUtils.isBlank(parentCode)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "上级节点");
			return;
		}
		String userId=request.getParameter("userId");
        if(StringUtils.isBlank(userId)){
        	AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户信息");
			return;
		}
		List<AppExaminateTheory> findList = appExaminateTheoryService.findList(entity);
		
		AppMockexamTheoryRecord record=new AppMockexamTheoryRecord();
		record.setQuestionId(parentCode);
		record.setUserId(userId);
		List<AppMockexamTheoryRecord> list = appMockexamTheoryRecordService.findList(record);
		List<String> ansList=new ArrayList<String>();
		for(AppMockexamTheoryRecord atr:list){
			String answerId = atr.getAnswerId();
			if(StringUtils.isNotBlank(answerId)){
				for(String key:answerId.split(",")){
					ansList.add(key);
				}
			}
		}	
		
		for(AppExaminateTheory model:findList){
			String id = model.getId();
			if(ansList.contains(id)){
				model.setChecked(true);
			}			
		}
		JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(findList));
		AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
	}
	@RequestMapping(value = "compute")
	public void compute(AppExaminateTheory entity,HttpServletRequest request,HttpServletResponse response) {
		String userId=request.getParameter("userId");
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户信息");
			return;
		}
		String theoryId=request.getParameter("theoryId");
        if(StringUtils.isBlank(theoryId)){
        	AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "理论标识");
			return;
		}
        String postId=request.getParameter("postId");
        if(StringUtils.isBlank(postId)){
        	AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "岗位类别");
			return;
        }
        AppMockexamTheoryRecord model=new AppMockexamTheoryRecord();
        model.setTheoryId(theoryId);
        model.setUserId(userId);        
		model.setPostId(postId);
        List<AppMockexamTheoryRecord> findList = appMockexamTheoryRecordService.findList(model);
        BigDecimal success=new BigDecimal(0);
        int error=0;
        int record=findList.size();
        if(findList!=null&&findList.size()>0){
        	for(AppMockexamTheoryRecord amtr:findList){
        		BigDecimal score = amtr.getScore();
        		if(score==null){
        			score=new BigDecimal(0.0);
        		}
        		success=success.add(score);
        	}
        }
        String theoryUserId=request.getParameter("theoryUserId");
        if(StringUtils.isNotBlank(theoryUserId)){
        	TmockexamTheoryUser ttu=new TmockexamTheoryUser();
        	ttu.setId(theoryUserId);
        	ttu.setScore(success);
    		if(success.doubleValue()>=60){
    			ttu.setType(2);
    		}else{
        	    ttu.setType(3);
    		}
        	tmockexamTheoryUserService.update(ttu);
        }
        JSONObject obj=new JSONObject();
        obj.put("success", success);
        obj.put("error", error);
        obj.put("record", record);
        AppController.renderSuccessObject(response, obj, MessageCode.SUCCESS_ACK);
	}
	public static void main(String[] args) {
		int a=5;
		int b=3;
		double c=(a+b)/b;
		BigDecimal b1 = new BigDecimal(Double.toString(b));
		BigDecimal b2 = new BigDecimal(Double.toString(a+b));
		
		BigDecimal doubleValue = b1.divide(b2);
		double doubleValue2 = doubleValue.multiply(new BigDecimal(Double.toString(100))).doubleValue();
		System.out.println(doubleValue2);

		
		System.out.println(c);
	}
}
